<template>
  <div class="GGSBody wap">
    <div class="bg"></div>
    <x-header v-if="!this.$fromApp(this)" :left-options="{backText: ''}">搭赠设置</x-header>
    <div class="main">
      <div class="GGSContent">
        <ul class="groups display-flex flex-direction-column">
          <li class="groupItem display-flex flex-direction-row align-items-center">
            <span class="groupTitle must">参与客户:</span>
            <input class="disInputM" type="text" disabled v-model="selectCustomerStr" style="text-indent: 10px;">
            <span class="choseBtn display-flex flex-direction-row align-items-center justify-content-flex-center"  @click="selectCustomer"><span>选择</span></span>
          </li>
          <li class="groupItem display-flex flex-direction-row align-items-center">
            <span class="groupTitle must">商品名称:</span>
            <input class="disInputM" type="text" disabled  v-model="selectedGoods.name" style="text-indent: 10px;">
            <span class="choseBtn display-flex flex-direction-row align-items-center justify-content-flex-center" @click="showPopupFn('0')"><span>选择</span></span>
          </li>
          <li class="groupItem display-flex flex-direction-row align-items-center">
            <span class="groupTitle">商品规格:</span>
            <input class="disInputM" type="text" disabled v-model="selectedGoods.spec" style="text-indent: 10px;">
          </li>
          <li class="groupItem display-flex flex-direction-row align-items-center">
            <span class="groupTitle must">赠品名称:</span>
            <input class="disInputM" type="text" disabled  v-model="selectedGoods1.name" style="text-indent: 10px;">
            <span class="choseBtn display-flex flex-direction-row align-items-center justify-content-flex-center" @click="showPopupFn('1')"><span>选择</span></span>
          </li>
          <li class="groupItem display-flex flex-direction-row align-items-center">
            <span class="groupTitle">赠品规格:</span>
            <input class="disInputM" type="text" disabled v-model="selectedGoods1.spec" style="text-indent: 10px;">
          </li>
          <li class="groupItem display-flex flex-direction-row align-items-center">
            <span class="groupTitle must">有效期:</span>
            <!--<datetime class="selectDate display-flex flex-direction-row align-items-center justify-content-flex-center" placeholder="选择日期"-->
                      <!--:start-date="nowDate" v-model="beginTime" @on-change="change" :style="{color:(beginTime==''?'#DDDDDD':'#000000')}"></datetime>-->
            <datetime class="selectDate" placeholder="选择日期" v-model="beginTime" format="YYYY-MM-DD HH:mm"
                      :start-date="nowDate" @on-change="change" :style="{color:(beginTime==''?'#DDDDDD':'#000000')}"></datetime>
            <span style="margin: 0 .2rem">至</span>
            <!--<datetime class="selectDate display-flex flex-direction-row align-items-center justify-content-flex-center" placeholder="选择日期"-->
                      <!--:start-date="beginTime" v-model="endTime" @on-change="change" :style="{color:(endTime==''?'#DDDDDD':'#000000')}"></datetime>-->
            <datetime class="selectDate" placeholder="选择日期" v-model="endTime" format="YYYY-MM-DD HH:mm"
                      :start-date="endTimeDef" @on-change="change" :style="{color:(endTime==''?'#DDDDDD':'#000000')}"></datetime>
          </li>
        </ul>
        <div class="conditionBox display-flex flex-direction-row">
          <div class="selectBox display-flex flex-direction-row">
            <span style="color: #FF3B47">*&nbsp;</span>
            <div class="selectBtnGroup display-flex flex-direction-row align-items-center">
              <p style="width: 45%;text-align: center" @click="selectCondition(0)"
                 :style="{color:(conditionType==0?'#FB6E52':'#C8CBD3')}">满</p>
              <p style="width: 2%;text-align: center;color: #C8CBD3">|</p>
              <p style="width: 51%;text-align: center" @click="selectCondition(1)"
                 :style="{color:(conditionType==1?'#FB6E52':'#C8CBD3')}">每满</p>
            </div>
          </div>
          <div class="conditionGroup">
            <ul class="display-flex flex-direction-column">
              <li class="conditionItem display-flex flex-direction-row align-items-center">
                <input class="conditionInput" type="number" v-model="initConditionData.num" @input="changeInput">
                <span>件，搭赠</span>
                <input class="conditionInput" type="number" v-model="initConditionData.giftNum" @input="changeInput"> <span>件</span>
                <img v-if="conditionType==1&&count<5" class="addBtn" @click="addCondition" src="../../../../assets/img/order/add.png" alt="">
              </li>
              <li class="conditionItem display-flex flex-direction-row align-items-center" v-if="conditionData!=''"
                  v-for="(item, index) in conditionData" :key="index">
                <input class="conditionInput" v-model="item.num" type="number" @input="changeInput">
                <span>件，搭赠</span>
                <input class="conditionInput" v-model="item.giftNum" type="number" @input="changeInput">
                <span>件</span>
                <img class="addBtn" @click="delCondition(index)" src="../../../../assets/img/order/delete.png" alt="">
              </li>
            </ul>
          </div>
        </div>
      </div>
      <div v-if="showBtn" class="setBtn display-flex flex-direction-row align-items-center justify-content-flex-center" @click="submitBtn">
        <span>确认</span>
      </div>
    </div>
    <x-dialog v-model="showToast" class="customerDialog">
      <ul class="customerList">
        <scroller class="customerListScroller">
          <li v-for="(item,index) in customerArr" @click="choseCustomerType(item)"
              :key="index" class="customerItem display-flex align-items-center">
            <img :src="item.select?require('../../../../assets/img/order/checkbox1.png'):require('../../../../assets/img/order/checkbox2.png')" alt="">
            <span>{{item.name}}</span>
          </li>
        </scroller>
      </ul>
      <div class="selectCustomerBtn display-flex flex-direction-row align-items-center justify-content-flex-center" @click="sureSelectCustomer">
        <span>确定</span>
      </div>
    </x-dialog>
    <popup class="selectGoodsBox" v-model="showPopup" position="right" width="100%">
      <div class="selectGoodsHead display-flex flex-direction-row align-items-center">
        <img class="vux-close" @click="closePopupFn" src="../../../../assets/img/order/close.png" alt="">
        <span class="selectGoodsTitle display-flex flex-direction-row align-items-center justify-content-flex-center"><span>选择商品</span></span>
      </div>
      <div class="searchBox display-flex flex-direction-row align-items-center">
        <input class="searchInput" type="text" v-model="searchKeyWord" :placeholder="searchIcon" @input="inputChange">
        <span class="searchBtn display-flex flex-direction-row align-items-center justify-content-flex-center" @click="searchGoods"><span>查询</span></span>
      </div>
      <div class="searchContent">
        <div class="searchTree" :style="{'height':this.$platform() == 1?'8.2rem':'8rem'}">
          <scroller style="position: relative">
            <div class="treeItem" v-for="(item,index) in goodsArr" :key="index">
              <div @click="openGoods(item)" class="treeParent display-flex flex-direction-row">
                <img v-if="item.open" src="../../../../assets/img/order/closeTree.png" alt="">
                <img v-else src="../../../../assets/img/order/openTree.png" alt="">
                <p>{{item.name}}</p>
              </div>
              <div v-if="item.open" class="treeChildren">
                <div v-for="(j,jIndex) in item.goodsList" :key="jIndex">
                  <div @click="selectGoods(j)" class="childrenItem display-flex flex-direction-row align-items-center" >
                    <img :src="selectGoodsId==j.id?require('../../../../assets/img/order/chose_1.png'):require('../../../../assets/img/order/chose_2.png')" alt="">
                    <p>[{{j.brandName}}] {{j.name}}</p>
                  </div>
                </div>
              </div>
            </div>
          </scroller>
        </div>
        <p v-if="showBtn" class="sureBtn display-flex flex-direction-row align-items-center justify-content-flex-center"  @click="sureSelect"><span>确认选中</span></p>
      </div>
    </popup>
  </div>
</template>

<script>
  import { Datetime, Popup } from 'vux'
    export default {
        name: "giftGiveSetting",
      components:{
        Datetime,
        Popup
      },
      data(){
          return{
            conditionType:0,
            initConditionData:{
              num:'',
              giftNum:''
            },
            conditionData:[],
            count:1,
            showPopup:false,
            showToast:false,
            customerArr:[],
            selectCustomerArr:[],
            selectCustomerNameArr:[],
            searchIcon:'\ue630 请输入商品名称',
            goodsArr:[],
            selectedGoods:{},
            selectedGoods1:{},
            selectGoodsId:-1,
            selectObj:{},
            selectObj1:{},
            popupType:'',
            beginTime:'',
            endTime:'',
            endTimeDef:'',
            nowDate:'',
            selectCustomerStr:'',
            searchKeyWord:'',
            showBtn:true,
            docmHeight:document.documentElement.clientHeight, //初始屏幕高度
          }
      },
      created(){
          this.getNowDate();
          this.getCustomer();
      },
      mounted(){
        if (this.$platform() == 1) {
          window.onresize=()=>{
            if(document.body.clientHeight<this.docmHeight){
              this.showBtn = false
              if (document.activeElement.tagName == "INPUT" || document.activeElement.tagName == "TEXTAREA") {
                setTimeout(function () {
                  document.activeElement.scrollIntoViewIfNeeded();
                }, 100);
              }
            }else{
              this.showBtn = true
            }
          }
        }
      },
      methods:{
          change (value) {
            // console.log('change', value)
            // console.log('change1', this.beginTime)
            // console.log('change2', this.endTime)
            // if(this.beginTime>this.endTime){
            //   this.endTime = this.beginTime;
            // }
            var beginStr =  this.beginTime + '';
            this.endTimeDef = beginStr.split(' ')[0];
          },
          changeInput(e){
            e.target.value = e.target.value.replace(/[^\D]/g,"");
          },
          inputChange(){
            this.searchKeyWord = this.searchKeyWord.replace(/[^\a-\z\A-\Z0-9\u4E00-\u9FA5\%&]/g, "");
          },
          getGoodsList(name=''){
            let api;
            switch(this.popupType){
              case '0':
                api = 'activity/seller/choose/goodsList'
                break;
              case '1':
                api = 'common/seller/goods_category/list'
                break;
            } 
            this.$ajax.get(api,res=>{
              if(res.code == '200'){
                for(let i=0;i<res.data.length;i++){
                  res.data[i].open = false
                }
                this.goodsArr = res.data;
                // console.log(this.goodsArr);
              }
            },{name:name,type:this.popupType == '0'?0:'',distributorCategoryIds: this.selectCustomerArr.join(',')})
          },
        searchGoods(){
          this.getGoodsList(this.searchKeyWord);
        },
          selectCondition(val){
            this.conditionType = val;
            this.initConditionData.num = '';
            this.initConditionData.giftNum = '';
            if(0==val){
              this.conditionData = [];
              this.count = 1;
            }
          },
          addCondition(){
            this.count++;
            let item = {
              num:'',
              giftNum:''
            }
            this.conditionData.push(item);
          },
          delCondition(val){
            this.count--;
            this.conditionData.splice(val,1);
          },
          getCustomer(){
            this.$ajax.get('common/seller/customer_category/list',res=>{
              if(res.code == '200'){
                for (let i = 0; i < res.data.length; i++){
                  res.data[i].select = false
                }
                this.customerArr = res.data;
              }else{
                this.$vux.toast.text(res.msg, 'center');
              }
            })
          },
          selectCustomer(){
            this.showToast = true;
            // this.selectCustomerArr = [];
            // this.selectCustomerNameArr = [];
            // this.selectCustomerStr = '';
            // this.$ajax.get('common/seller/customer_category/list',res=>{
            //   if(res.code == '200'){
            //     for (let i = 0; i < res.data.length; i++){
            //       res.data[i].select = false
            //     }
            //     this.customerArr = res.data;
            //   }else{
            //     this.$vux.toast.text(res.msg, 'center');
            //   }
            // })
          },
          choseCustomerType(item){
            item.select = !item.select;
            let typeIndex = this.selectCustomerArr.indexOf(item.id);
            let typeNameIndex = this.selectCustomerNameArr.indexOf(item.name);
            if(typeIndex >= 0){
              this.selectCustomerArr.splice(typeIndex,1);
              this.selectCustomerNameArr.splice(typeNameIndex,1);
            }else {
              this.selectCustomerArr.push(item.id)
              this.selectCustomerNameArr.push(item.name)
            }
          },
          showPopupFn(val){
            if(!this.selectCustomerArr || !this.selectCustomerArr.length){
              this.$vux.toast.text('请选择参与客户', 'center');
              return;
            }
            this.popupType = val;
            this.showPopup = true;
            if(val == '0'){
              this.selectGoodsId = this.selectedGoods.id;
            }else{
              this.selectGoodsId = this.selectedGoods1.id;
            }
            this.getGoodsList();
          },
          closePopupFn(){
            this.showPopup = false;
            this.searchKeyWord = '';
            if(this.popupType == '0'){
              this.selectGoodsId = this.selectedGoods.id;
            }else{
              this.selectGoodsId = this.selectedGoods1.id;
            }
          },
          openGoods(item){
            item.open = !item.open;
          },
          selectGoods(item){
            this.selectGoodsId = item.id;
            if(this.popupType == '0'){
              this.selectObj = item;
            }else{
              this.selectObj1 = item;
            }
          },
          sureSelect(){
            this.showPopup = false;
            if(this.popupType == '0'){
              this.selectedGoods = this.selectObj;
              // console.log('选择的商品信息：',this.selectedGoods)
            }else{
              this.selectedGoods1 = this.selectObj1;
              // console.log('选择的赠品信息：',this.selectedGoods1)
            }
          },
        sureSelectCustomer(){
          this.showToast=false;
          this.selectCustomerStr = this.selectCustomerNameArr.join('，');
          console.log(this.selectCustomerArr);
        },
        resetData(){
          this.beginTime = '';
          this.endTime = '';
          this.selectGoodsId = -1;
          this.conditionType = 0;
          this.customerArr = [];
          this.selectCustomerArr = [];
          this.selectCustomerNameArr = [];
          this.conditionData = [];
          this.initConditionData.num = '';
          this.initConditionData.giftNum = '';
          this.selectedGoods = {};
          this.selectedGoods1 = {};
          this.selectCustomerStr = '';
        },
        submitBtn(){
          let finalResult = [];
          finalResult.push(this.initConditionData)
          if(this.conditionType==1){
            finalResult = finalResult.concat(this.conditionData);
          }

          if(!this.selectedGoods.id){
            this.$vux.toast.text('请选择商品！', 'center');
            return;
          }
          if(!this.selectedGoods1.id){
            this.$vux.toast.text('请选择赠品！', 'center');
            return;
          }
          if(this.beginTime==''){
            this.$vux.toast.text('请选择开始时间！', 'center');
            return;
          }
          if(this.endTime==''){
            this.$vux.toast.text('请选择结束时间！', 'center');
            return;
          }
          if(this.beginTime>this.endTime){
            this.$vux.toast.text('开始时间不能大于结束时间！', 'center');
            return;
          }
          if(this.selectCustomerArr == ''){
            this.$vux.toast.text('请选择参与客户！', 'center');
            return;
          }

          for (let i =0; i<finalResult.length; i++){
            if(finalResult[i].giftNum!=''&&finalResult[i].num!=''){
              if(finalResult[i].giftNum==0||finalResult[i].num==0){
                this.$vux.toast.text('搭赠件数必须大于0！', 'center');
                return;
              }
              if(finalResult[i].giftNum.indexOf('.')!=-1||finalResult[i].num.indexOf('.')!=-1){
                this.$vux.toast.text('只能输入整数！', 'center');
                return;
              }
            }else{
              this.$vux.toast.text('请设置完整搭赠规则！', 'center');
              return;
            }
          }

          let params = {
            beginTime:this.beginTime,
            endTime:this.endTime,
            buyGoodsId:this.selectedGoods.id,
            giftGoodsId:this.selectedGoods1.id,
            giveRule:this.conditionType,
            giftRuleList:finalResult,
            distributorCategoryIds:this.selectCustomerArr
          }


          this.$ajax.post('activity/full_gift/submit',params,res=>{
            // console.log(res);
            if(res.code == '200'){
              this.$vux.toast.text('设置成功', 'center');
              this.resetData();
              if(this.$fromApp(this)){
                this.$callJava({code:1003,quick :true})
              }else{
                this.$router.go(-1);
              }
            }else{
              this.$vux.toast.text(res.msg, 'center');
            }
          },1)
        },
        getNowDate(){
          var date = new Date();
          var seperator1 = "-";
          var year = date.getFullYear();
          var month = date.getMonth() + 1;
          var strDate = date.getDate();
          if (month >= 1 && month <= 9) {
            month = "0" + month;
          }
          if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
          }
          var monthFirstDay =  year + seperator1 + month + seperator1 + '01';
          var currentdate = year + seperator1 + month + seperator1 + strDate;
          this.nowDate = currentdate+'';
        }
      }
    }
</script>

<style lang="less" type="text/less" scoped>
  ul>li{
    list-style: none;
  }
  input{
    -webkit-appearance: none;
  }
  .must::before{
    content: '* ';
    color: #FF3B47;
  }
  .addBtn{
    width: .38rem;
    height: .38rem;
    margin-left: .2rem;
  }
  .delBtn{
    width: .38rem;
    height: .38rem;
    margin-left: .2rem;
  }
.GGSBody{
  .bg{
    position: fixed;
    width: 100%;
    height: 100%;
    background-color: #FFFFFF;
    z-index: -1;
  }
  background-color: #FFFFFF;
  .GGSContent{
    width: 6.9rem;
    margin-left: .3rem;
    .groups{
      margin: .3rem 0;
      padding-bottom: .1rem;
      border-bottom: 1px solid #EBEBEB;
      .groupItem{
        height: .66rem;
        margin-bottom: .2rem;
        .groupTitle{
          width: 1.6rem;
          text-align: right;
          margin-right: .3rem;
        }
        .disInputM{
          width: 3.5rem;
          height: .64rem;
          white-space: nowrap;
          -ms-text-overflow: ellipsis;
          text-overflow: ellipsis;
          border: 1px solid #DDDDDD;
          border-radius: 4px;
        }
        .choseBtn{
          width: 1.36rem;
          height: .66rem;
          border-radius: 4px;
          line-height: .66rem;
          text-align: center;
          color: #FFFFFF;
          background-color: #8E919F;
          margin-left: .1rem;
        }
        .selectDate{
          width: 2rem;
          height: .82rem;
          /*line-height: .64rem;*/
          border: 1px solid #DDDDDD;
          border-radius: 4px;
          text-align: center;
          padding: 0;
          font-size: 13px;
        }
      }
    }
    .conditionBox{
      .selectBox{
        width: 2rem;
        .selectBtnGroup{
          width: 1.48rem;
          height: .64rem;
          border: 1px solid #C8CBD3;
          border-radius: 4px;
        }
      }
      .conditionGroup{
        width: 5.4rem;
        .conditionItem{
          height: .66rem;
          .conditionInput{
            width: 1.26rem;
            height: .64rem;
            margin: 0 .1rem;
            text-align: center;
            border: none;
            outline: none;
            border-bottom: 1px solid #DDDDDD;
          }
        }
      }
    }
  }
  .setBtn{
    position: fixed;
    bottom: .3rem;
    left: .3rem;
    width: 6.9rem;
    height: 0.92rem;
    border-radius: 0.46rem;
    color: #ffffff;
    font-size: 17px;
    background-color: #527DD9;
    text-align: center;
    line-height: 0.92rem;
    margin-top: 1rem;
  }
  .customerDialog{
    .customerList{
      width: 80%;
      height: 4rem;
      margin-left: 10%;
      margin-top: .3rem;
      .customerListScroller{
        margin:.5rem .5rem 1rem;
        height: 4rem!important;
        .customerItem{
          width: 100%;
          height: .8rem;
          img{
            width: .36rem;
            height: .36rem;
            margin-right: .4rem;
            margin-left: .2rem;
          }
          span{
            color: #333333;
            font-size: 17px;
            width: 3.8rem;
            text-overflow: ellipsis;
            white-space: nowrap;
            overflow: hidden;
            text-align: left;
          }
        }
      }
    }
    .selectCustomerBtn{
      width: 2.54rem;
      height: .84rem;
      color: #FFFFFF;
      font-size: 17px;
      text-align: center;
      line-height: .84rem;
      border-radius: .42rem;
      background-color: #527DD9;
      margin: .2rem 0 .2rem 3rem;
    }
  }
  .selectGoodsBox{
    background-color: #FFFFFF;
    .selectGoodsHead{
      width: 100%;
      height: .88rem;
      line-height: .88rem;
      border-bottom: 1px solid #EDEDED;
      font-size: 18px;
      .vux-close{
        width: .3rem;
        height: .3rem;
        margin-left: .5rem;
        margin-right: .3rem;
      }
      .selectGoodsTitle{
        font-weight: bold;
      }
    }
    .searchBox{
      width: 100%;
      height: .7rem;
      margin-top: .3rem;
      .searchInput{
        outline: none;
        width: 5.38rem;
        height: .68rem;
        border: 1px solid #C8CBD3;
        border-radius: 3px;
        margin-left: .3rem;
        margin-right: .1rem;
        text-indent: .3rem;
        -webkit-appearance: none;
        font-size: 15px;
      }
      .searchInput::placeholder{
        color:#c6c6c6;
        font-size:15px;
        font-family: "iconfont" !important;
      }
      .searchInput::-moz-placeholder{
        color:#c6c6c6;
        font-size:15px;
        font-family: "iconfont" !important;
      }
      .searchInput::-webkit-input-placeholder{
        color:#c6c6c6;
        font-size:15px;
        font-family: "iconfont" !important;
      }
      .searchBtn{
        width: 1.38rem;
        height: .68rem;
        text-align: center;
        line-height: .68rem;
        color: #868999;
        background-color: #C8CBD3;
        border-radius: 3px;
        border: 1px solid #C8CBD3;
      }
    }
    .searchContent{
      .searchTree{
        width: 6.5rem;
        /*height: 8.6rem;*/
        margin: .5rem;
        .treeItem{
          margin: .2rem .1rem;
          .treeParent{
            img{
              width: .2rem;
              height: .2rem;
              padding: .1rem;
              border: 1px solid #DDDDDD;
            }
            p{
              color: #333333;
              font-size: 15px;
              margin-left: .3rem;
            }
          }
          .treeChildren{
            margin-left: .5rem;
            .childrenItem{
              margin: .2rem 0;
              color: #333333;
              font-size: 15px;
              img{
                width: .36rem;
                height: .36rem;
                margin-right: .3rem;
              }
            }
          }
        }
      }
      .sureBtn{
        width: 6.2rem;
        height: .84rem;
        line-height: .84rem;
        text-align: center;
        border-radius: .42rem;
        color: #FB6E52;
        font-size: 17px;
        border: 1px solid #FB6E52;
        /*margin-left: .6rem;*/
        position: fixed;
        left: 50%;
        bottom: .3rem;
        margin-left: -3.1rem;
      }
    }
  }
}

</style>
